package collection;

import java.util.Arrays;
import java.util.Iterator;

public class MyArrayList implements Iterable<Integer>{
    private  int [] data;
    private  int initCapacity = 10;
    private int size;
    public MyArrayList(){
        this(10);
    }
    public MyArrayList(int initCapacity){
        this.initCapacity = initCapacity;
        this.data = new int[0];
    }
    public void add(int value){
        ensureCapacity();
        data[size++] = value;
    }
    private void ensureCapacity() {
        if(data.length==0){
            data = new int[this.initCapacity];
            return;
        }
        if(size >= data.length){
            int newCapacity = data.length + (data.length>>1);
            this.data = Arrays.copyOf(data,newCapacity);
        }
    }

    public void remove(int index){
        checkIndex(index);
        if(index == size-1){
            size--;
            return;
        }
        System.arraycopy(data,index+1,data,index,size-index-1);
        size--;
    }
    public int get(int index){
        checkIndex(index);
        return data[index];
    }

    private void checkIndex(int index) {
        if(index<0 || index >=size ){
            throw new ArrayIndexOutOfBoundsException("下标越界");
        }
    }

    public void set(int index,int value){
        checkIndex(index);
        data[index] = value;    //把index位置的值替换成新的值
    }

    //迭代器iterator
    public Iterator<Integer> iterator(){
        return new Iterator<Integer>() {
            int index = 0;
            @Override
            public boolean hasNext() {
                return index<size;
            }
            @Override
            public Integer next() {
                int tmp = data[index];
                index++;
                return tmp;
            }
        };
    }
    public int size(){
        return this.size;

    }
    public static void main(String[] args) {
        MyArrayList list = new MyArrayList();
        for (int i = 0; i < 18; i++) {
            list.add(i);
        }
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

        System.out.println("------------");
        list.remove(5);
        list.remove(12);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        list.set(3,3333);
        System.out.println("------------");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println("--------------------迭代器");
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        System.out.println("foreach------------");
        for (Integer a: list) {
            System.out.println(a);
        }
    }
}
